home *** CD-ROM | disk | FTP | other *** search
- Path: ix.netcom.com!netnews
- From: miker3@ix.netcom.com (Mike Rubenstein)
- Newsgroups: comp.lang.c
- Subject: Re: Please help ?!
- Date: Sat, 27 Jan 1996 13:12:53 GMT
- Organization: Netcom
- Message-ID: <310a2389.49571776@nntp.ix.netcom.com>
- References: <4dm889$3hs@neptunus.pi.net> <4drnv1$cr@news.iag.net> <4drq5i$cr@news.iag.net> <4e6hse$dvl@ns.RezoNet.NET>
- NNTP-Posting-Host: ix-dc9-18.ix.netcom.com
- X-NETCOM-Date: Sat Jan 27 5:12:58 AM PST 1996
- X-Newsreader: Forte Agent .99c/16.141
-
- ray@ultimate-tech.com (Ray Dunn) wrote:
-
- > In referenced article, John R Buchan says...
- > >> cpy = (char *) malloc(MAXLEN);
- > >
- > >The cast is unnecessary and can hide errors. You should remove it.
- >
- > This is the second time I've seen this advice in the last five minutes
- > in the newsgroup.
- >
- > Certainly the cast is unnecessary, and certainly *some* unnecessary
- > casts can hide errors, but casting the result of malloc can *never*
- > hide an error, because it's telling the compiler to do something it
- > would do anyway.
- >
- > On the other hand, if by any chance "cpy" is not a "char *", but you
- > thought it was when you wrote the statement, then including the cast
- > will *catch* an error.
- >
- > I'd go as far as to say that if the argument of malloc, calloc,
- > etc. contains a sizeof operator such that a number of elements of that
- > type are being allocated, then adding a cast to a pointer of the same
- > type to the malloc return is the *safest* thing you can do:
- >
- > fred = malloc(n * sizeof(int));
- >
- > Oops - fred isn't an "int *" it's a "long *", but the compiler wont
- > issue any warnings, but in:
- >
- > fred = (int *)malloc(n * sizeof(int));
- >
- > the compiler will issue an error.
-
- Why will the compiler issue an error in that case? It's completely
- legal code.
-
- The error that can be hidden by a cast is omitting the declaration of
- malloc() and not including stdlib.h. Without the cast a diagnostic is
- required since an int cannot be automatically converted to a pointer.
- With the cast the compiler will convert the int it thinks is returned
- by malloc() to a pointer and few compilers will give any indication of
- the error (read: none that I'm aware of).
-
-
- Michael M Rubenstein
-